package com.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;

import com.bean.Users;

public class MyServer extends ServerSocket {
	protected static ArrayList<Users> User_List = new ArrayList<Users>(); 
	protected static ArrayList<Thread> Threader = new ArrayList<Thread>(); 
	protected static ArrayList<Socket> socketList = new ArrayList<Socket>();
	protected static LinkedList Message_Array = new LinkedList(); 
	protected static int Thread_Counter = 0; 
	protected static boolean isClear = true; 
	protected static Boolean isOnlien = false;
	protected static final int SERVER_PORT = 9999; 
	protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true); 
	private String xml;
	public MyServer() throws IOException {
		super(SERVER_PORT);
		xml = "<cross-domain-policy>";
        xml = xml + "<allow-access-from domain=\"127.0.0.1\" to-ports=\"9999,8000\" />";
        xml = xml + "<allow-access-from domain=\"localhost\" to-ports=\"9999,8000\" />";
        xml = xml + "<allow-access-from domain=\"192.168.1.110\" to-ports=\"9999,8000\" />";
        xml = xml + "</cross-domain-policy>";

		new Broadcast();
		//new BroadOnLine();
		//append connection log 
		Calendar now = Calendar.getInstance(); 
		String str = "[" + now.getTime().toString() + "] Accepted a connection\015\012"; 
		byte[] tmp = str.getBytes(); 
		LOG_FILE.write(tmp); 
		
		File file = new File("src/config.xml");
		FileInputStream fis = new FileInputStream(file);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		try {
			while(true) {
				Socket s = accept();
				BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
				PrintWriter pw = new PrintWriter(s.getOutputStream());
				char[] by = new char[22];
				br.read(by, 0, 22);
				String line = new String(by);
				if(line.equals("<policy-file-request/>")) {
					//pw.print(xml+"\0");
					pw.print(new String(b) + "\0");
					pw.flush();
				}else {
					new ServerThread(s);
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	/**
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		new MyServer();
	}

}
